package com.irdstudio.efp.esb.api.rest.ms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.irdstudio.efp.basic.framework.mq.constant.TagEnums;
import com.irdstudio.efp.basic.framework.mq.constant.TopicEnums;
import com.irdstudio.efp.esb.api.bean.yx.ReqMsYxApprNoticeBean;
import com.irdstudio.efp.esb.api.bean.yx.RespMsYxApprNoticeBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.GroupeInterface.ms;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.MsLoanConstant;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


/**
 * 需求编号：xxxxxx<br/>
 * 问题编号：<br/>
 * 功能描述：
 * 服务名称：30220007
 * 服务场景名称：08
 * 本服务用于风控决策平台通知网贷马上金融渠道用户用信审批结果<br/>
 * 开发人员：tiankg<br/>
 * 创建时间：2020/5/14 17:37
 * @Version 1.0
 * @Since 1.0
 */
@RestController
@RequestMapping("/esb")
public class MsLoanApprNoticeResultController {

    private static Logger logger = LoggerFactory.getLogger(MsLoanApprNoticeResultController.class);
    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request
     *            请求对象集合
     * @return
     * @author huangwb
     * @since 2019年1月20日 下午1:28:08
     * @version 1.0
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("获取ESB请求对象，校验 ESB请求系统头和请求应用头对象开始");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request
     *            请求对象集合
     * @return
     * @author tiankg
     * @since 2020年5月13日
     * @version 1.0
     */
    @ModelAttribute("reqMsYxApprNoticeBean")
    public ReqMsYxApprNoticeBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("获取马上用信审批结果通知请求对象，校验马上用信审批结果通知请求体对象开始");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqMsYxApprNoticeBean.class);
    }

    @PostMapping("/SERVICE_30220007_08")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated({ms.class}) @ModelAttribute("reqMsYxApprNoticeBean") ReqMsYxApprNoticeBean reqMsYxApprNoticeBean, BindingResult br2, Exception exception)
            throws Exception {

            String applySeq = reqMsYxApprNoticeBean.getAppNo();//申请编号
            logger.info("===============>马上用信审批结果通知接口调用开始，申请流水号== " + applySeq + " <====================");

            try{
                // 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息
                if (Objects.nonNull(exception)) {
                    throw exception;
                }
                String result = reqMsYxApprNoticeBean.getAprvlRsltFlg();//审批结果标识：Y通过/N拒绝
                String bReason = reqMsYxApprNoticeBean.getRfsRsnMainCls();//拒绝原因大类
                String sReason = reqMsYxApprNoticeBean.getRfsRsnSbcls();//拒绝原因小类

                if(!"N".equals(result) && !"Y".equals(result)){//校验审批结果标识是否正确传入
                    return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                            JSON.toJSONString(buildRespNoticeOfResultBean(EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "审批结果标识不正确")),
                            EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "审批结果标识不正确");
                }

                if ("N".equals(result)){//审批结果为拒绝时，校验拒绝原因是否正确传入
                    if (StringUtil.isNullorBank(bReason)){
                        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                                JSON.toJSONString(buildRespNoticeOfResultBean(EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "拒绝原因大类不能为空")),
                                EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "拒绝原因大类不能为空");
                    }else if (StringUtil.isNullorBank(sReason)){
                        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                                JSON.toJSONString(buildRespNoticeOfResultBean(EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "拒绝原因小类不能为空")),
                                EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "拒绝原因小类不能为空");
                    }else if (bReason.length() + sReason.length() >= 500){
                        return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                                JSON.toJSONString(buildRespNoticeOfResultBean(EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "拒绝原因大、小类总长度过长")),
                                EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), "拒绝原因大、小类总长度过长");
                    }
                }

                NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
                nlsApplyInfoVO.setApplySeq(applySeq);
                NlsApplyInfoVO nlsApplyInfoVO1 = nlsApplyInfoService.queryByPk(nlsApplyInfoVO);//查询网贷基础信息表信息
                Objects.requireNonNull(nlsApplyInfoVO1,"马上用信审批结果通知获取到网贷申请基本信息为空");

                if ("Y".equals(result)){//用信审批通过
                    logger.info("马上用信审批结果通知接口调用成功");
                    updateNlsApplyInfo(nlsApplyInfoVO1,"","2", "");

                    producerService.sendMsg(new Message(TopicEnums.QUEUE_TASK_TOPIC.getTopicId(), TagEnums.TAG_QUEUE_TASK.getTagId(), applySeq.concat("+1"),
                            JSON.toJSONString(nlsApplyInfoVO1).getBytes("UTF-8")));//发送消息进行客户建档
                }else {//用信审批拒绝
                    updateNlsApplyInfo(nlsApplyInfoVO1,bReason +"—"+ sReason,"3",MsLoanConstant.NlsApplyStateEnum.REJECT.getVALUE());

                    producerService.sendMsg(new Message(TopicEnums.QUEUE_TASK_TOPIC.getTopicId(), TagEnums.TAG_QUEUE_TASK.getTagId(), applySeq.concat("+2"),
                            JSON.toJSONString(nlsApplyInfoVO1).getBytes("UTF-8")));//发送消息进行审批拒绝通知
                }

                return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                        JSON.toJSONString(buildRespNoticeOfResultBean(EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "通知成功！")),
                        EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "通知成功！");

            }catch (Exception e){
                logger.error("***********马上用信审批结果通知接口调用失败**************"+e.getMessage());
                e.printStackTrace();
                return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                        JSON.toJSONString(buildRespNoticeOfResultBean(EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), e.getMessage())),
                        EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), e.getMessage());
            }finally {
                logger.error("===============>马上用信审批结果通知接口调用结束，申请流水号== " + applySeq + " <====================");
            }

    }

    private void updateNlsApplyInfo(NlsApplyInfoVO nlsApplyInfoVO,String refuseMsg,String soltStage,String nlsApplyState) throws BizException {
        try {
            nlsApplyInfoVO.setRefuseCause(refuseMsg);
            nlsApplyInfoVO.setSoltStage(soltStage);
            if (!StringUtil.isNullorBank(nlsApplyState)){
                nlsApplyInfoVO.setNlsApplyState(nlsApplyState);
            }
            nlsApplyInfoService.updateByPk(nlsApplyInfoVO);
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException("更新用信审批结果时发生异常！");
        }

    }



    /**
     * 马上用信审批结果通知请求接口的返回对象
     *
     * @param retStCd
     *            返回状态码
     * @param rtnMsg
     *            返回信息
     * @return
     * @author tiankg
     * @since 2020年5月14日
     * @version 1.0
     */
    private static RespMsYxApprNoticeBean buildRespNoticeOfResultBean(String retStCd, String rtnMsg) {
        RespMsYxApprNoticeBean respMsYxApprNoticeBean = new RespMsYxApprNoticeBean();
        respMsYxApprNoticeBean.setRetCd(retStCd);
        respMsYxApprNoticeBean.setRetMsg(rtnMsg);
        return respMsYxApprNoticeBean;
    }

    @Autowired
    @Qualifier("nlsApplyInfoService")
    private NlsApplyInfoService nlsApplyInfoService;

    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;

}
